package com.wolfalpha.utron.net;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ApiClient {
    String TAG = "Client";
    public static String PHPSESSID = null;
    // 全局的网络连接客户端
    private DefaultHttpClient httpClient = null;

    public ApiClient() {
        // 创建一个默认的客户端
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 30 * 1000);
        HttpConnectionParams.setSoTimeout(httpParams, 30 * 1000);
        httpClient = new DefaultHttpClient();
    }

    // 发送get请求
    synchronized public String sendGetResquest(String url) {
        Log.d("url", url);

        HttpGet httpGet = new HttpGet(url);
        //第一次一般是还未被赋值，若有值则将SessionId发给服务器
        if (null != PHPSESSID) {
            System.out.println(PHPSESSID);
            httpGet.setHeader("Cookie", "SESSIONID=" + PHPSESSID);
        }
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int rCode = httpResponse.getStatusLine().getStatusCode();
            if (rCode == HttpStatus.SC_OK) {
//				System.out.println(EntityUtils.toString(httpResponse.getEntity()));
                if (PHPSESSID == null) {
                    CookieStore mCookieStore = httpClient.getCookieStore();
                    List<Cookie> cookies = mCookieStore.getCookies();
                    for (int i = 0; i < cookies.size(); i++) {
                        //这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
                        if ("SESSIONID".equals(cookies.get(i).getName())) {
                            PHPSESSID = cookies.get(i).getValue();
                            System.out.println(PHPSESSID);
                            break;
                        }

                    }
                }
                // 连接成功
                return EntityUtils.toString(httpResponse.getEntity());
            } else {
                return null;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            Log.d(TAG, "net disconnected");
            e.printStackTrace();
        }
        return null;
    }

    // 发送post请求
    synchronized public String sendPostResquest(String url, Map<String, String> params) {
        Log.d("url", url);
        // Post参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        // 遍历map将参数加入
        for (Map.Entry<String, String> mp : params.entrySet()) {
            list.add(new BasicNameValuePair(mp.getKey(), mp.getValue()));
        }

        HttpPost httpPost = new HttpPost(url);
        //第一次一般是还未被赋值，若有值则将SessionId发给服务器
        if (null != PHPSESSID) {
            System.out.println(PHPSESSID);
            httpPost.setHeader("Cookie", "SESSIONID=" + PHPSESSID);
        }
        try {
            // 对参数进行编码
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,
                    "utf-8");
            httpPost.setEntity(entity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            int rCode = httpResponse.getStatusLine().getStatusCode();
            if (rCode == HttpStatus.SC_OK) {
//				System.out.println(httpResponse.getEntity());
                if (PHPSESSID == null) {
                    CookieStore mCookieStore = httpClient.getCookieStore();
                    List<Cookie> cookies = mCookieStore.getCookies();
                    for (int i = 0; i < cookies.size(); i++) {
                        //这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
                        if ("SESSIONID".equals(cookies.get(i).getName())) {
                            PHPSESSID = cookies.get(i).getValue();
                            System.out.println(PHPSESSID);
                            break;
                        }

                    }
                }
                // 连接成功
                return EntityUtils.toString(httpResponse.getEntity());
            } else {
                return null;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            Log.d(TAG, "net disconnected");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传文件至服务器
     *
     * @param uploadUrl
     * @return
     * @throws Exception
     */
    synchronized public String uploadFile(String uploadUrl, Map<String, String> mp, Map<String, File> files) {
        HttpPost httppost = new HttpPost(uploadUrl);
        try {
            System.out.println(uploadUrl);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            if (files != null) {
                for (String key : files.keySet()) {
                    File file = files.get(key);
                    FileBody fileBody = new FileBody(file);
                    entity.addPart(key, fileBody);
                }
            }
            if (mp != null) {
                for (String key : mp.keySet()) {
                    ContentBody strBody = null;
                    try {
                        strBody = new StringBody(mp.get(key));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    entity.addPart(key, strBody);
                }
            }
            httppost.setEntity(entity);
            HttpResponse response = httpClient.execute(httppost);

            HttpEntity resEntity = response.getEntity();
            System.out.println(resEntity);
            if (resEntity == null) {
                System.out.println("null");
                return null;
            } else {
                return EntityUtils.toString(resEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("null");
        return null;
    }


    /**
     * 根据一个网络连接(URL)获取bitmap图像
     *
     * @param imageUri
     * @return
     */
    public Bitmap getusericon(String imageUri) {
        // 显示网络上的图片
        URL myFileUrl = null;
        try {
            myFileUrl = new URL(imageUri);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        Bitmap bitmap = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

}